package com.zuowei.ycy.user.ui.index;

import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.and.yzy.frame.adapter.AdapterCallback;
import com.and.yzy.frame.util.RetrofitUtils;
import com.and.yzy.frame.view.dialog.FormBotomDialogBuilder;
import com.orhanobut.logger.Logger;
import com.zuowei.ycy.R;
import com.zuowei.ycy.user.adapter.BuinessNoSortAdapter;
import com.zuowei.ycy.user.adapter.BusinessSortAdapter;
import com.zuowei.ycy.user.adapter.LeftMenuAdapter;
import com.zuowei.ycy.user.adapter.ShopCarAdapter;
import com.zuowei.ycy.user.config.UserManger;
import com.zuowei.ycy.user.domain.BusinessSortChoose;
import com.zuowei.ycy.user.domain.BusinessSortInfo;
import com.zuowei.ycy.user.domain.LeftMenuInfo;
import com.zuowei.ycy.user.http.Merchant;
import com.zuowei.ycy.ui.BaseFgt;
import com.zuowei.ycy.user.ui.login.LoginAty;
import com.zuowei.ycy.user.ui.order.CommitOrderAty;
import com.zuowei.ycy.user.util.AppJsonUtil;
import com.zuowei.ycy.user.util.Arith;
import com.zuowei.ycy.user.view.pinnedheaderlistview.PinnedHeaderListView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.Bind;
import butterknife.OnClick;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Response;


/**
 * 商品分类
 */
public class BusinessSortChooseFgt extends BaseFgt implements AdapterCallback {
    @Bind(R.id.lv_Left)
    ListView lv_Left;
    @Bind(R.id.lv_right)
    PinnedHeaderListView lv_right;
    @Bind(R.id.lv_right_on_sort)
    ListView mRight_no_sort;


    /**
     * 商品数量
     */
    @Bind(R.id.tv_number)
    TextView mTvNumber;
    /**
     * 商品总价格
     */
    @Bind(R.id.tv_price)
    TextView mTvPrice;
    /**
     * 配送费
     */
    @Bind(R.id.tv_take_price)
    TextView mTvTakePrice;

    /**
     * 如果添加了商品就显示该布局
     */
    @Bind(R.id.ll_have)
    LinearLayout mLlHave;
    /**
     * 没有添加商品的布局显示
     */
    @Bind(R.id.tv_empey_message)
    TextView mTvEmpeyMessage;

    /**
     * 提交按钮
     */
    @Bind(R.id.tv_commit)
    TextView mTvCommit;

    /**
     * 添加商品的底部布局
     */
    @Bind(R.id.ll_add_car)
    LinearLayout ll_add_car;
    private LayoutInflater inflater;


    @Bind(R.id.ll_empty)
    LinearLayout ll_empty;
    /**
     * 左边菜单栏
     */
    private LeftMenuAdapter mMenuAdapter;
    private BusinessSortAdapter rightAdapter;

    //保存左右对应的坐标
    private HashMap<Integer, Integer> hash = new HashMap<Integer, Integer>();
    private HashMap<Integer, Integer> hash1 = new HashMap<Integer, Integer>();


    FormBotomDialogBuilder mDialogBuilder;

    private String merchant_id;

    /**
     * 起送价
     */
    private double lowest_price;
    /**
     * 配送价
     */
    private double delivery_fee;

    /**
     * 选择商品的总价格
     */
    private double price;
    /**
     * 选择商品的总个数
     */
    private int count;


    @Override
    public int getLayoutId() {
        return R.layout.business_good_sort_choose_layout;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        showLoadingContentDialog();
    }

    @Override
    public void requestData() {
        merchant_id = getActivity().getIntent().getExtras().getString("merchant_id");
        lv_right.setEmptyView(ll_empty);
        isShowToast = false;
        doHttp(RetrofitUtils.createApi(Merchant.class).merchantGoodsList(merchant_id, UserManger.getM_id(), "0"), 1);


    }


    @Override
    public void initData() {
        inflater = LayoutInflater.from(getActivity());

        lv_right.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                BusinessSortInfo sortInfo = (BusinessSortInfo) parent.getItemAtPosition(position);
                Bundle bundle = new Bundle();
                bundle.putString("goods_id", sortInfo.getGoods_id());
                bundle.putString("good_name", sortInfo.getGoods_name());
                startActivity(GoodDetailAty.class, bundle);

            }
        });
    }


    /**
     * 弹窗提交按钮
     */
    private TextView tv_dialog_commit;
    /**
     * 弹窗商品数量
     */
    private TextView tv_dialog_select_number;
    /**
     * 弹窗商品总价
     */
    private TextView tv_dialog_price;
    /**
     * 弹窗配送费
     */
    private TextView tv_dialog_take_price;
    /**
     * 弹窗清空
     */
    private TextView tv_dialog_clear;
    /**
     * 弹窗列表
     */
    private ListView listView_dialog;
    private ShopCarAdapter shopCarAdapter;
    /**
     * 购物车列表
     */
    ArrayList<BusinessSortInfo> shopCarInfos;

    @OnClick({R.id.rl_gouwuche, R.id.tv_commit})
    @Override
    public void btnClick(View view) {
        super.btnClick(view);
        switch (view.getId()) {
            case R.id.rl_gouwuche:
                if (mDialogBuilder == null) {
                    mDialogBuilder = new FormBotomDialogBuilder(getActivity());
                    View addChar = LayoutInflater.from(getActivity()).inflate(R.layout.index_add_shopcar_pop, null, false);

                    listView_dialog = (ListView) addChar.findViewById(R.id.lv_car);

                    tv_dialog_commit = (TextView) addChar.findViewById(R.id.tv_commit);
                    tv_dialog_price = (TextView) addChar.findViewById(R.id.tv_price);
                    tv_dialog_clear = (TextView) addChar.findViewById(R.id.tv_clear);
                    tv_dialog_select_number = (TextView) addChar.findViewById(R.id.tv_select_num);
                    tv_dialog_take_price = (TextView) addChar.findViewById(R.id.tv_take_price);


                    tv_dialog_commit.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (UserManger.isLogin()) {
                                Bundle bundle = new Bundle();

                                bundle.putString("merchant_id", merchant_id);
                                bundle.putDouble("delivery_fee", delivery_fee);
                                bundle.putString("count", count + "");
                                bundle.putString("price", Arith.add(delivery_fee, price) + "");
                                bundle.putParcelableArrayList("data", shopCarInfos);

                                startActivity(CommitOrderAty.class, bundle);
                            } else {

                                startActivity(LoginAty.class, null);
                            }
                        }
                    });

                  RelativeLayout iv_diamiss = (RelativeLayout) addChar.findViewById(R.id.rl_gouwuche);

                    iv_diamiss.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            mDialogBuilder.dismiss();
                        }
                    });

                    tv_dialog_clear.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {


                            shopCarAdapter.removeAll();
                            shopCarInfos.clear();
                            for (BusinessSortInfo businessSortInfo : rightAdapter.findAll()) {

                                businessSortInfo.setNumber(0);

                            }
                            rightAdapter.notifyDataSetChanged();
                            updatePrice();
                            updateDialogPrice();
                            mDialogBuilder.dismiss();

                        }
                    });
                    shopCarInfos = new ArrayList<>();

                    for (BusinessSortInfo businessSortInfo : rightAdapter.findAll()) {

                        if (businessSortInfo.getNumber() > 0) {
                            shopCarInfos.add(businessSortInfo);
                        }

                    }

                    updateDialogPrice();

                    shopCarAdapter = new ShopCarAdapter(getActivity(), shopCarInfos, R.layout.index_add_car_item, this);

                    listView_dialog.setAdapter(shopCarAdapter);

                    mDialogBuilder.setFB_AddCustomView(addChar);
                } else {
                    shopCarAdapter.removeAll();
                    shopCarInfos.clear();
                    shopCarInfos = null;
                    shopCarInfos = new ArrayList<>();
                    for (BusinessSortInfo businessSortInfo : rightAdapter.findAll()) {

                        if (businessSortInfo.getNumber() > 0) {
                            shopCarInfos.add(businessSortInfo);
                        }
                    }

                    shopCarAdapter.addAll(shopCarInfos);
                    updateDialogPrice();
                }


                if (mDialogBuilder.isShowing()) {
                    mDialogBuilder.dismiss();

                } else {

                    mDialogBuilder.show();

                }
                break;
            case R.id.tv_commit:

                if (UserManger.isLogin()) {

                    if (shopCarInfos==null){
                        shopCarInfos=new ArrayList<>();

                    }
                    shopCarInfos.clear();
                    for (BusinessSortInfo businessSortInfo : rightAdapter.findAll()) {

                        if (businessSortInfo.getNumber() > 0) {
                            shopCarInfos.add(businessSortInfo);
                        }
                    }
                    Bundle bundle = new Bundle();
                    bundle.putString("merchant_id", merchant_id);
                    bundle.putDouble("delivery_fee", delivery_fee);
                    bundle.putString("count", count + "");
                    bundle.putString("price", Arith.add(delivery_fee, price) + "");
                    bundle.putParcelableArrayList("data", shopCarInfos);
                    startActivity(CommitOrderAty.class, bundle);
                } else {

                    startActivity(LoginAty.class, null);
                }


                break;


        }
    }

    private void updateDialogPrice() {


        tv_dialog_select_number.setText(count + "");
        tv_dialog_price.setText("￥" + price);
        tv_dialog_take_price.setText("(配送费￥" + delivery_fee + ")");

        //如果没有达到起送价
        if (price < lowest_price) {
            tv_dialog_commit.setText("还差￥" + (Arith.sub(lowest_price,price)));
            tv_dialog_commit.setBackgroundColor(getResources().getColor(R.color.empty_bg));
            tv_dialog_commit.setEnabled(false);
        } else {

            tv_dialog_commit.setText("选好了");
            tv_dialog_commit.setBackgroundColor(getResources().getColor(R.color.toolbar_bg));
            tv_dialog_commit.setEnabled(true);

        }


    }

    @Override
    public boolean setIsInitRequestData() {
        return true;
    }

    @Override
    public void adapterstartActivity(Class<?> className, Bundle options) {

    }

    @Override
    public void adapterstartActivityForResult(Class<?> className, Bundle options, int requestcode) {

    }

    @Override
    public void adapterInfotoActiity(Object data, int what) {

        switch (what) {
            case 0:
                int position = (int) data;
                rightAdapter.isScroll = false;
                lv_right.setSelection(hash.get(position));
                break;
            case 1:
                updatePrice();
                break;
            case 3:

                int pos = (int) data;

                BusinessSortInfo carInfo = shopCarAdapter.getItem(pos);
                if (carInfo.getNumber() == 0) {

                    shopCarAdapter.removeInfo(carInfo);

                    if (shopCarAdapter.findAll().size() == 0) {
                        mDialogBuilder.dismiss();
                    }

                }
                rightAdapter.notifyDataSetChanged();


                updatePrice();
                updateDialogPrice();


                break;


        }


    }


    private void updatePrice() {

        price = 0;
        count = 0;

        for (BusinessSortInfo businessSortInfo : rightAdapter.findAll()) {

            count += businessSortInfo.getNumber();
            price  = Arith.add(Arith.mul(businessSortInfo.getNumber(),Double.parseDouble(businessSortInfo.getGoods_price())),price);

        }

        //如果商品数量为0
        if (count == 0) {

            mLlHave.setVisibility(View.GONE);
            mTvEmpeyMessage.setVisibility(View.VISIBLE);
            mTvCommit.setText("还差￥" + lowest_price);
            mTvCommit.setBackgroundColor(getResources().getColor(R.color.empty_bg));
            mTvCommit.setEnabled(false);
        } else {


            mLlHave.setVisibility(View.VISIBLE);
            mTvNumber.setText(count + "");
            mTvPrice.setText("￥" + price);
            mTvTakePrice.setText("(配送费￥" + delivery_fee + ")");
            mTvEmpeyMessage.setVisibility(View.GONE);
            //如果没有达到起送价
            if (price < lowest_price) {
                mTvCommit.setText("还差￥" + (Arith.sub(lowest_price,price)));
                mTvCommit.setBackgroundColor(getResources().getColor(R.color.empty_bg));
                mTvCommit.setEnabled(false);
            } else {

                mTvCommit.setText("选好了");
                mTvCommit.setBackgroundColor(getResources().getColor(R.color.toolbar_bg));
                mTvCommit.setEnabled(true);

            }


        }


    }


    @Override
    public void onSuccess(String result, Call<ResponseBody> call, Response<ResponseBody> response, int what) {


        BusinessSortChoose sortChoose = AppJsonUtil.getObject(result, BusinessSortChoose.class);

        if (sortChoose.getGoods_list().size() == 0) {


            lv_right.setVisibility(View.GONE);
            lv_Left.setVisibility(View.GONE);
            ll_empty.setVisibility(View.VISIBLE);


        } else {
            lowest_price = Double.parseDouble(sortChoose.getLowest_price());
            delivery_fee = Double.parseDouble(sortChoose.getDelivery_fee());
            initGoods(initMenu(sortChoose.getGoods_list()));
            updatePrice();
        }


        super.onSuccess(result, call, response, what);
    }


    @Override
    public void onFailure(String result, Call<ResponseBody> call, Response<ResponseBody> response, int what) {
        BusinessSortChoose sortChoose = AppJsonUtil.getObject(result, BusinessSortChoose.class);

        if (sortChoose.getGoods_list().size() == 0) {

            lv_right.setVisibility(View.GONE);
            lv_Left.setVisibility(View.GONE);
            ll_empty.setVisibility(View.VISIBLE);

        }
        super.onFailure(result, call, response, what);
    }

    /**
     * 没有分类时加载
     *
     * @param take_out_list
     */
    private void initNoSort(List<BusinessSortInfo> take_out_list) {
        lv_Left.setVisibility(View.GONE);
        lv_right.setVisibility(View.GONE);
        if (take_out_list.size() > 0) {
            take_out_list.get(take_out_list.size() - 1).setIsLast(true);
        }

        BuinessNoSortAdapter outAdapter = new BuinessNoSortAdapter(getActivity(), take_out_list, R.layout.buiness_good_sort_choose_item, this);

        mRight_no_sort.setAdapter(outAdapter);

    }


    /**
     * 初始化产品列表
     *
     * @param take_out_list
     */
    private void initGoods(List<BusinessSortInfo> take_out_list) {

        rightAdapter = new BusinessSortAdapter(getActivity(), take_out_list, this);
        lv_right.setAdapter(rightAdapter);


        View HeaderView = inflater.inflate(R.layout.index_business_title_item,
                lv_right, false);
        lv_right.setPinnedHeader(HeaderView);

        lv_right.setOnScrollListener(rightAdapter);
        rightAdapter.setAdapterCallback(this);
        rightAdapter.setLeftListView(lv_Left, hash1);
    }


    /**
     * 初始化分类导航
     *
     * @param
     */
    private List<BusinessSortInfo> initMenu(List<BusinessSortInfo> take_out_list) {

        List<LeftMenuInfo> take_out_menu = new ArrayList<>();

        for (int i = 0; i < take_out_list.size(); i++) {
            String menuString = take_out_list.get(i).getG_t_name();
            if (i == 0) {
                LeftMenuInfo leftMenuInfo = new LeftMenuInfo();
                leftMenuInfo.setMenu_name(menuString);
                take_out_menu.add(leftMenuInfo);
            }
            boolean isHava = false;
            for (int j = 0; j < take_out_menu.size(); j++) {
                String old = take_out_menu.get(j).getMenu_name();

                if (old.equals(menuString)) {
                    isHava = true;
                    break;
                }

            }

            if (!isHava) {
                LeftMenuInfo leftMenuInfo = new LeftMenuInfo();
                leftMenuInfo.setMenu_name(menuString);
                take_out_menu.add(leftMenuInfo);

            }

        }

        take_out_menu.get(0).setIsSelect(true);

        if (mMenuAdapter == null) {
            mMenuAdapter = new LeftMenuAdapter(getActivity(), take_out_menu, R.layout.index_left_menu_item, this);
            lv_Left.setAdapter(mMenuAdapter);
        } else {
            mMenuAdapter.removeAll();
            mMenuAdapter.addAll(take_out_menu);
        }


        List<List<BusinessSortInfo>> allSprt = new ArrayList<>();
        List<BusinessSortInfo> list = new ArrayList<>();


        for (int i = 0; i < take_out_menu.size(); i++) {
            List<BusinessSortInfo> temp = new ArrayList<>();
            for (int j = 0; j < take_out_list.size(); j++) {

                if (take_out_menu.get(i).getMenu_name().equals(take_out_list.get(j).getG_t_name())) {

                    temp.add(take_out_list.get(j));
                }


            }

            allSprt.add(temp);
        }

        for (int i = 0; i < allSprt.size(); i++) {
            for (int k = 0; k < allSprt.get(i).size(); k++) {
                list.add(allSprt.get(i).get(k));
            }
        }


        Logger.i("allSprt.size()==" + allSprt.size());
        hash.clear();
        hash1.clear();
        int tempSize = 0;
        for (int i = 1; i <= take_out_menu.size(); i++) {

            int goodSize = allSprt.get(i - 1).size();
            Log.i("result", "size==" + goodSize);

            for (int j = 0; j < goodSize; j++) {

                hash.put(i - 1, tempSize);

                hash1.put(tempSize, i);

                allSprt.get(i - 1).get(j).setType(i);

                if (j == goodSize - 1) {
                    allSprt.get(i - 1).get(j).setIsLast(true);
                }
            }

            tempSize += goodSize;
        }

        return list;
    }


}



